package client

import (
	awesomeTask "awesomeTask/commom"
	"awesomeTask/commom/MessageHelper"
	"awesomeTask/config"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	"awesomeTask/system/log"
	"net"
)

var Nodes map[string]ClientHandle = map[string]ClientHandle{}

/**
子节点的连接句柄
*/
type ClientHandle struct {
	IpAddress   string
	CpuNum      float64
	Memory      float64
	FreeMemory  float64
	RunningTask int
	UsedCpu     float64
	Connetion   net.Conn
	IsInit      bool
	IsMaster    bool
	UniqueId    string
	BindIp      string
	BindPort    int
	Location    interface{}
}

func CreateInfo(event string, sendInfo map[string]interface{}) string {
	sendInfo["event"] = event
	return helper.JsonEncode(sendInfo)
}

/**
请求当前某个子节点当前节点的状态
*/
func (client ClientHandle) AskClientSendCurrentStatus() {
	sendData := make(map[string]interface{})
	sendDataString := CreateInfo("PostNodeStatus", sendData)
	client.Connetion.Write(awesomeTask.PacketData([]byte(sendDataString)))
	log.GetLogger().Info("向服务器发送当前的资源信息" + helper.JsonEncode(sendData))
}

/**
任务到客户端
*/
func (client ClientHandle) PushTask(taskInfo interface{}) bool {
	sendData := make(map[string]interface{})
	sendData["taskInfo"] = taskInfo
	return MessageHelper.SendEvent("RunTask", sendData, client.Connetion)
}

/**
关闭当前连接
*/
func (client ClientHandle) Close() {
	err := client.Connetion.Close()
	if err != nil {
		panic(err.Error())
	}
	log.GetLogger().Info("客户端断开连接:" + client.IpAddress)
	delete(Nodes, client.IpAddress)
}

/**
计算某个节点的系统资源
*/
func (client *ClientHandle) GetCurrentResourceScore() float64 {
	return client.FreeMemory + client.CpuNum - client.UsedCpu
}
func InitNode(IpAddress string, conn net.Conn) ClientHandle {
	return ClientHandle{
		IpAddress: IpAddress,
		IsInit:    false,
		Connetion: conn,
	}
}

func GetNodeByUniqueId(uniqueId string) net.Conn {
	for _, item := range Nodes {
		if item.UniqueId == uniqueId {
			return item.Connetion
		}
	}
	return nil
}

func GetBestNode() ClientHandle {
	bestNode := make(map[string]interface{})
	for _, node := range Nodes {
		if bestNode["node"] == nil {
			bestNode["node"] = node
			bestNode["score"] = node.GetCurrentResourceScore()
			continue
		}
		score := node.GetCurrentResourceScore()
		if score > bestNode["score"].(float64) {
			bestNode["node"] = node
			bestNode["score"] = node.GetCurrentResourceScore()
		}
		if score == bestNode["score"].(float64) && helper.RandInt(0, 10)%2 == 0 {
			bestNode["node"] = node
			bestNode["score"] = node.GetCurrentResourceScore()
		}
	}
	if bestNode["node"] == nil {
		panic("master process failed find useful node")
	}
	return bestNode["node"].(ClientHandle)
}
func GetConnectInfos() map[string]ClientHandle {
	return Nodes
}

/**
获取节点当前的信息
*/
func GetNodeStaus() map[string]interface{} {
	status := kernel.GetKernelDriver().GetNodeCpuUseAndMemory()
	status["bindIp"] = config.GetConfigByKey("listenIpAddress")
	status["bindPort"] = config.GetConfigByKey("listenPort")
	status["location"] = config.GetConfigByKey("location")
	return status
}
